package by.bucha.testproject.fragments;

import by.bucha.testproject.R;
import by.bucha.testproject.adapters.ParsedXmlListAdapter;
import by.bucha.testproject.app.MainTabActivity;
import by.bucha.testproject.content.ContentManager;
import by.bucha.testproject.response.CallbackAsyncTask;
import by.bucha.testproject.xml.bo.ResultModel;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.ListFragment;
import android.widget.Toast;

public class ParsedXmlListFragment extends ListFragment {

	private ParsedXmlListAdapter mAdapter;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		mAdapter = new ParsedXmlListAdapter(getActivity()
				.getApplicationContext(),
				R.layout.view_fragment_parsed_xml_list, null);
		this.setListAdapter(mAdapter);
		ContentManager.getInstance().getResponse(
				new CallbackAsyncTask<ResultModel>() {

					@Override
					public void onSuccess(ResultModel obj) {
						if (obj != null && obj.getListQuoteLength() != 0) {
							mAdapter.changeData(obj.getListQuote());
							refreshView();
						} else {
							String warning = getActivity()
									.getApplicationContext()
									.getResources()
									.getString(
											R.string.parsed_xml_list_fragment_strings_no_data);

							Toast.makeText(
									getActivity().getApplicationContext(),
									warning, Toast.LENGTH_SHORT).show();
						}
					}

					@Override
					public void onError(Exception e) {
						String warning = getActivity()
								.getApplicationContext()
								.getResources()
								.getString(
										R.string.parsed_xml_list_fragment_strings_exception);

						Toast.makeText(getActivity().getApplicationContext(),
								warning + ": " + e.getMessage(),
								Toast.LENGTH_SHORT).show();
					}
				});
	}

	private void refreshView() {
		Fragment currentFragment = getFragmentManager().findFragmentByTag(
				MainTabActivity.TAG_PARSED_XML);
		FragmentTransaction fragTransaction = getFragmentManager()
				.beginTransaction();
		fragTransaction.detach(currentFragment);
		fragTransaction.attach(currentFragment);
		fragTransaction.commit();
	}
}
